<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="processKey" label="流程定义">
          <FIInput v-model="state.query.processKey" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="appId" label="发起系统ID">
          <FIInput v-model="state.query.appId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="appCode" label="发起系统代码">
          <FIInput v-model="state.query.appCode" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="moduleCode" label="发起模块代码">
          <FIInput v-model="state.query.moduleCode" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="mapperId"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="true"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
      @on-cell-select="selectClick"
      @on-cell-click="beforeSelClick"
    >
      <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          beforePopText="请选择一条数据"
          buttonText="删除"
          :btn-binds="{ id: 'delete', border: true }"
          style="margin-right: 10px"
          @confirm="deleteRow"
        />
        <FIButton id="import" border @click="importDiag = true"></FIButton>
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
      
    </FITable>
    <FIModel v-model="importDiag" width="500" title="数据权限配置导入" @confirm="uploadSure">
      <FIUpload @upload="uploadFunc"></FIUpload>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryApp,
  apiQueryModule,
  apiQueryProcessesDef,
  apiQueryBizType,
  apiFormCfgQueryForm,
  apiFormCfgDeleteForm,
  apiFormCfgSaveForm,
  apiFormCfgExportForm,
  apiFormCfgimportForm,
} from '@/api/modules/EW.js'
const route = useRoute()
const menuShow = ref(false)
const importDiag = ref(false)
const searchWrapperSpan = 8
const processShow = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'FormCfg'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const appDataList = ref([])
const moduleDataList = ref([])
const proDefDataList = ref([])
const bizTypeDataList = ref([])
const userlistCurrent = ref(1)
const appPageCurrent = ref(1)
const bizPageCurrent = ref(1)
const modulesPageCurrent = ref(1)
const formPageCurrent = ref(1)
const loadMoreEnd = ref(false)
const state = reactive({
  query: {
    processKey: '',
    appCode: '',
    appId: '',
    moduleCode: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  // {
  //   label: '流程定义编码',
  //   prop: 'processKey',
  //   align: 'center',
  //   editable: true,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '流程定义编码',
    prop: 'processKey',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/BpmProcessDef/queryProcessesDef',
        props: { value: 'processDefinitionKey', label: 'processDefinitionKey' },
        displayKey: ['processDefinitionKey', 'processDefinitionName'],
        searchParam: 'processKeyOrName',
      },
    },
  },
  {
    label: '流程定义名称',
    prop: 'processName',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '发起应用代码',
  //   prop: 'appCode',
  //   align: 'center',
  //   editable: true,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '发起应用代码',
    prop: 'appCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryApp',
        props: { value: 'appCode', label: 'appCode' },
        displayKey: ['appCode', 'appName'],
        searchParam: 'appQuery',
        // apiParams: {
        //   current: 1,
        //   size: 10,
        //   appQuery: '',
        // },
      },
    },
  },
  {
    label: '发起应用名称',
    prop: 'appName',
    align: 'center',
    editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '发起模块代码',
  //   prop: 'moduleCode',
  //   align: 'center',
  //   editable: true,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '发起模块代码',
    prop: 'moduleCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryModule',
        props: { value: 'moduleCode', label: 'moduleCode' },
        displayKey: ['moduleCode', 'moduleName'],
        searchParam: 'moduleQuery',
        apiParams: {
          current: 1,
          size: 10,
          appId:'',
          moduleQuery: '',
        },
      },
    },
  },
  {
    label: '发起模块名称',
    prop: 'moduleName',
    align: 'center',
    editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '发起业务类型代码',
  //   prop: 'biztypeCode',
  //   align: 'center',
  //   editable: true,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '发起业务类型代码',
    prop: 'biztypeCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryBizType',
        props: { value: 'biztypeCode', label: 'biztypeCode' },
        displayKey: ['biztypeCode', 'biztypeName'],
        searchParam: 'biztypeCode',
        apiParams: {
          current: 1,
          size: 10,
          appId:'',
          moduleId:'',
          biztypeCode: '',
        },
      },
    },
  },
  {
    label: '发起业务类型名称',
    prop: 'biztypeName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程节点表单ID',
    prop: 'nodeFormId',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '页面应用代码',
  //   prop: 'formAppCode',
  //   align: 'center',
  //   editable: true,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '页面应用代码',
    prop: 'formAppCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryApp',
        props: { value: 'appCode', label: 'appCode' },
        displayKey: ['appCode', 'appName'],
        searchParam: 'appQuery',
      },
    },
  },
  {
    label: '页面应用名称',
    prop: 'formAppName',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '应用页面URL',
    prop: 'appFormUrl',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '备注',
    prop: 'remark',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'isTop', type: 'top' }],
  // },
])

const checkedRows = ref([])
const uploadFile = reactive({}) //导入的对象
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const appCodeloadMore = () => {
  console.log(loadMoreEnd.value, 'loadMoreEnd')
  console.log(appPageCurrent.value, 'appPageCurrent')
  if (loadMoreEnd.value && appPageCurrent.value > 1) return
  appPageCurrent.value++
  queryAppFunc()
}
//导入
const uploadFunc = (file) => {
  console.log(toRaw(file), '查看')
  uploadFile.value = file
  console.log(uploadFile, '查看')
}
//点确定
const uploadSure = () => {
  const list = toRaw(uploadFile.value)
  uploadApiFn(list.raw)
}
const uploadApiFn = (file) => {
  let par = {
    file: file,
  }
  apiFormCfgimportForm(par)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch(() => {})
}

//流程定义列表

const queryProDefFunc = () => {
  let par = {
    processDefinitionName: '',
    processDefinitionKey: '',
    size: 10,
    current: userlistCurrent.value,
  }
  apiQueryProcessesDef(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        // proDefDataList.value = res.data.data.result
        proDefDataList.value = proDefDataList.value.concat(res.data.data.result)
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
//应用系统查询
const queryAppFunc = () => {
  let par = {
    appCode: '',
    appName: '',
    size: 10,
    current: appPageCurrent.value,
  }
  apiQueryApp(par)
    .then((res) => {
      console.log(res, 'res-------')
      isTableLoading.value = false
      if (res.data.success) {
        // appDataList.value = res.data.data.result
        appDataList.value = appDataList.value.concat(res.data.data.result)
        if (appPageCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
//应用模块列表查询
const queryModuleFunc = () => {
  let par = {
    moduleCode: '',
    moduleName: '',
    size: 10,
    current: modulesPageCurrent.value,
  }
  apiQueryModule(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        // moduleDataList.value = res.data.data.result
        moduleDataList.value = moduleDataList.value.concat(res.data.data.result)
        if (modulesPageCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
//业务类型查询
const queryBizTypeFunc = () => {
  let par = {
    biztypeCode: '',
    biztypeName: '',
    size: 10,
    current: bizPageCurrent.value,
  }
  apiQueryBizType(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        // bizTypeDataList.value = res.data.data.result
        bizTypeDataList.value = bizTypeDataList.value.concat(res.data.data.result)
        if (bizPageCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const beforeSelClick = (scope) => {
  console.log(scope, '查看555')
  if (scope.column.property == 'appCode') {
    if (!scope.row.appCode) {
      
      tableRef.value.cloneColumnList[scope.cellIndex + 1].editConfig.otherBinds.disabled = true
    } else {
      tableRef.value.cloneColumnList[scope.cellIndex + 1].editConfig.otherBinds.disabled = false
      // tableRef.value.cloneColumnList[scope.cellIndex + 1].editConfig.otherBinds.apiParams.appQuery =
      //   scope.row.appCode
    }
  }
  if (scope.column.property == 'moduleCode') {
    if (!scope.row.appCode) {
      tableRef.value.cloneColumnList[scope.cellIndex + 1].editConfig.otherBinds.disabled = true
    }else{
      console.log(tableRef.value.cloneColumnList[scope.cellIndex - 1],']]]')
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = false
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.appId =
        scope.row.appId
    }
  }
  if (scope.column.property == 'biztypeCode') {
    console.log(tableRef.value.cloneColumnList[scope.cellIndex],'=====')
    if (!scope.row.moduleCode) {
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = true
    }else{
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.disabled = false
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.moduleId =
        scope.row.moduleId
      tableRef.value.cloneColumnList[scope.cellIndex - 1].editConfig.otherBinds.apiParams.appId =
        scope.row.appId
    }
  }
}
const selectClick = (scope, item) => {
  console.log(scope, item, '查看')
  if (scope.column.property == 'processKey') {
    tableRef.value.setCellValue(scope.$index, 'processName', item.processDefinitionName)
    tableRef.value.setCellValue(scope.$index, 'processKey', item.processDefinitionKey)
  }
  if (scope.column.property == 'appCode') {
    tableRef.value.setCellValue(scope.$index, 'appName', item.appName)
    tableRef.value.setCellValue(scope.$index, 'appId', item.appId)
  }
  if (scope.column.property == 'moduleCode') {
    tableRef.value.setCellValue(scope.$index, 'moduleName', item.moduleName)
    tableRef.value.setCellValue(scope.$index, 'moduleId', item.moduleId)
  }
  if (scope.column.property == 'biztypeCode') {
    tableRef.value.setCellValue(scope.$index, 'biztypeName', item.biztypeName)
    tableRef.value.setCellValue(scope.$index, 'biztypeId', item.biztypeId)
  }
  if (scope.column.property == 'formAppCode') {
    tableRef.value.setCellValue(scope.$index, 'formAppName', item.appName)
    tableRef.value.setCellValue(scope.$index, 'formAppId', item.appId)
  }
}
//导出
const exportClick = () => {
  apiFormCfgExportForm(state.query)
}
//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.mapperId) ids.push(item?.mapperId)
    })
  isTableLoading.value = true
  apiFormCfgDeleteForm({ mapperId: ids })
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
//操作
const actionClick = (item, rowData, btnInfo) => {}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiFormCfgQueryForm(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  console.log(checkedRows.value,'checkedRows')
  apiFormCfgSaveForm(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
//   const exportRow = () => {
//     apiGroupUserExport(state.query)
//   }
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
  queryModuleFunc()
  queryAppFunc()
  queryProDefFunc()
  queryBizTypeFunc()
})
</script>
<style lang="less" scoped></style>
